package com.cnhis.cloudhealth.clinical.clidoctor.cliregistration.bo;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cnhis.cloudhealth.clinical.clidoctor.cliparamter.dao.CliParamterDao;
import com.cnhis.cloudhealth.clinical.clidoctor.cliregistration.dao.RegistDao;
import com.cnhis.cloudhealth.commons.Mappers.ModelVo;
import com.cnhis.cloudhealth.commons.cardmember.bo.CardMemberMangerBo;
import com.cnhis.cloudhealth.commons.exception.ExBaseException;
import com.cnhis.cloudhealth.commons.newid.GetNewId;
import com.cnhis.cloudhealth.commons.utils.DateUtils;
import com.cnhis.cloudhealth.commons.utils.GlobalVariable;
import com.cnhis.cloudhealth.commons.utils.JsonUtil;
import com.cnhis.cloudhealth.commons.utils.Page;
import com.cnhis.cloudhealth.commons.utils.StaticKeys;
import com.cnhis.cloudhealth.commons.utils.jpinyin.PinyinHelper;
import com.cnhis.cloudhealth.rate.base.vac1.bo.RateVac1Bo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class RegistBo
{
    @Resource
    private RegistDao registDao;
    
    @Resource
    private CliParamterDao cliParamterDao;
    
    @Resource
    private GetNewId getNewId;
    
    @Autowired
    private RateVac1Bo rateVac1Bo;
    
    @Autowired
    private CardMemberMangerBo cardMemberMangerBo;
    
    
    public ModelVo getDoctorRegistrationType(int currPage, int pageSize, Map<String, Object> param)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        Page pg = null;
        try
        {
            pg = registDao.getDoctorRegistrationType(param, currPage, pageSize);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(pg.getList());
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setTotal(pg.getTotalNumber());
        mo.setRows(pg.getList());
        return mo;
    }
    
    public ModelVo getDepartmentsRegistrationType(int currPage, int pageSize)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        Page pg = null;
        try
        {
            pg = registDao.getDepartmentsRegistrationType(currPage, pageSize);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(pg.getList());
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setTotal(pg.getTotalNumber());
        mo.setRows(pg.getList());
        return mo;
    }
    
    public ModelVo setUIElements()
        throws Exception
    {
        ModelVo mo = new ModelVo();
        List list = null;
        try
        {
            list = registDao.setUIElements();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(list);
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setRows(list);
        return mo;
    }
    
    public ModelVo getItemsOfRegistrationType(Map map, int currPage, int pageSize)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        Page pg = null;
        try
        {
            pg = registDao.getItemsOfRegistrationType(map, currPage, pageSize);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(pg.getList());
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setTotal(pg.getTotalNumber());
        mo.setRows(pg.getList());
        return mo;
    }
    
    public ModelVo registrationTypeDefaultChargeType(Map map)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        List list = null;
        try
        {
            list = registDao.registrationTypeDefaultChargeType(map);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(list);
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setRows(list);
        return mo;
    }
    
    public ModelVo hospitalFeeRebate(Map map, int currPage, int pageSize)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        Page pg = null;
        try
        {
            pg = registDao.hospitalFeeRebate(map, currPage, pageSize);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(pg.getList());
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setTotal(pg.getTotalNumber());
        mo.setRows(pg.getList());
        return mo;
    }
    
    public ModelVo settingDefaultType(Map map)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        List list = null;
        try
        {
            list = registDao.settingDefaultType(map);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(list);
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setRows(list);
        return mo;
    }
    
    public ModelVo patientFeeType(Map map)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        List list = null;
        try
        {
            list = registDao.patientFeeType(map);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(list);
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setRows(list);
        return mo;
    }
    
    public ModelVo selectType(Map map, int currPage, int pageSize)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        Page pg = null;
        try
        {
            pg = registDao.selectType(map, currPage, pageSize);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(pg.getList());
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setTotal(pg.getTotalNumber());
        mo.setRows(pg.getList());
        return mo;
    }
    
    public ModelVo selectPatientType(Map map, int currPage, int pageSize)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        Page pg = null;
        try
        {
            pg = registDao.selectPatientType(map, currPage, pageSize);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(pg.getList());
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setTotal(pg.getTotalNumber());
        mo.setRows(pg.getList());
        return mo;
    }
    
    public ModelVo expandInfo(int currPage, int pageSize)
        throws Exception
    {
        ModelVo mo = new ModelVo();
        Page pg = null;
        try
        {
            pg = registDao.expandInfo(currPage, pageSize);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
        mo.setList(pg.getList());
        mo.setResult(StaticKeys.OH_SUCCESS);
        mo.setTotal(pg.getTotalNumber());
        mo.setRows(pg.getList());
        return mo;
    }
    
    @SuppressWarnings({"unused", "rawtypes", "unchecked"})
    public ModelVo save(Map<String, Object> params) throws Exception
    {
        ModelVo mo = new ModelVo();
        String mydata = (String)params.get("mydata");
        Map map1 = convertJson(mydata);
        List iar1List = registDao.queryForList("CliRegistration.hasIar1",map1);
        if(iar1List !=null && iar1List.size()>0)
        {
            mo.setResult(StaticKeys.OH_FALSE);
            mo.setResultMsg("此病人本次就诊已存在医保结账记录，不允许修改保险号和险种名称！");
            return mo;
        }
        Long vaa01 = getNewId.nextId();
        Long vac01 = getNewId.nextId();
        Long vai01 = getNewId.nextId();
        if (map1.get("lVAA01")==null)
        {
            map1.put("lVAA01", vaa01);
        }
        map1.put("lVAC01", vac01);
        map1.put("lVAI01", vai01);
        map1.put("lVAI04", "GH"+vai01);
        Object vac41 = map1.get("lVAC41");
        if(vac41!=null && !"".equals(vac41.toString()))
        {
            map1.put("lVAC41", Timestamp.valueOf(vac41.toString()));
        }
        else
        {
        	map1.put("lVAC41", null);
        }
        if(map1.get("lVAA47")!=null)
        {
            map1.put("lVAC27", map1.get("lVAA47"));
        }
        String vaa12 = GlobalVariable.StringIsNull(map1.get("lVAA12"));
        if(!"".equals(vaa12))
        {
            map1.put("lVAA12", Timestamp.valueOf(vaa12));
        }
        else
        {
            map1.put("lVAA12", null);
        }
        String vaa10 = GlobalVariable.StringIsNull(map1.get("lVAA10"));
        if("".equals(vaa10))
        {
            map1.put("lVAA10", 0);
        }
        String vcj15 = GlobalVariable.StringIsNull(map1.get("lVCJ15"));
        if("".equals(vcj15))
        {
            map1.put("lVCJ15", 0);
        }
        String grid2rows = (String)params.get("grid2rows");
        List list1 = parserToMap(grid2rows);
        List<Long> vaj01s = getNewId.nextId(list1.size());
        double vaj37_sum = 0;
        for(int i = 0;i<list1.size();i++)
        {
            Map temp = (Map)list1.get(i);
            temp.put("lVAJ01", vaj01s.get(i));
            temp.put("lVAA01", vaa01);
            temp.put("lVAC01", vac01);
            temp.put("lVAI01", vai01);
            Object vaj37 = temp.get("vaj37");
            if(vaj37!=null && !"".equals(vaj37.toString()))
            {
                vaj37_sum = vaj37_sum + Double.parseDouble(vaj37.toString());
            }
            else
            {
                vaj37_sum += 0;
            }
        }
        map1.put("lVAJ37",vaj37_sum);
        map1.put("list1", list1);
        int totalNum = 1;
        List obj0 = null;
        try
        {
            obj0 = registDao.queryVaa1(map1);
            
            // 判断病人性别是否符合科室性别限制
            Object obj = registDao.queryBck1BySexAndBck01(map1);
            if (obj != null)
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("当前科室" + params.get("") + "限制只能挂性别为" + params.get("") + "的病人");
                return mo;
            }
            // 查询公共参数--简易挂号病人当天是否只能挂一次号
            Map<String, Object> temp = new HashMap<String, Object>();
            temp.put("productId", 100);
            temp.put("programId", 105002);
            temp.put("paramno", 253);
            String publicPara1 = cliParamterDao.getSysParamValue(temp);
            if (publicPara1!=null && Integer.parseInt(publicPara1) == 1)
            {
                // 简易挂号病人当天是否只挂了一次号
                Object obj1 = registDao.queryVac1ByConditions(map1);
                if (obj != null)
                {
                    mo.setResult(StaticKeys.OH_FALSE);
                    mo.setResultMsg("同一个病人当天同一个科室只能挂号一次，此病人已挂号，不能重复挂号");
                    return mo;
                }
            }
            
            // 病人是否满足免挂号条件
            // 获取病人免挂号岁数限制
            Map<String, Object> temp1 = new HashMap<String, Object>();
            temp.put("productId", 100);
            temp.put("programId", 105002);
            temp.put("paramno", 367);
            String publicPara2 = cliParamterDao.getSysParamValue(temp);
            Object obj2 = registDao.queryBBY1ByConditions(map1);
            if (publicPara2!=null)
            {
                int parseInt = Integer.parseInt(publicPara2);
                if (parseInt > 0 && "Y".equals(params.get("lAAU01"))
                    && Integer.parseInt(params.get("lVAA10").toString()) >= parseInt)
                {
                    if (obj2 != null)
                    {
                        // 删除病人费用明细表的挂号费用
                        registDao.deleteBBY1ByConditions(map1);
                    }
                } 
            }
            // 根据病人ID计算就诊次数
            // 如果挂号记录表存在病人ID，计算就诊次数
            Object obj3 = registDao.queryVac71(map1);
            if (obj3 != null)
            {
                totalNum = Integer.parseInt(obj3.toString()) + 1;
                params.put("totalNum", totalNum);
            }
            // 门诊号如果为空，生成门诊号
            /*Object obj4 = registDao.queryVaa03(map1);
            if (obj4 == null)
            {
                params.put("VAA03", vaa01+"");
            }
            else
            {
                params.put("VAA03", obj4.toString());
            }*/
            
            String vac68 = GetAgeDetailFromAge(0, "Y", DateUtils.String2Date(GlobalVariable.StringIsNull(map1.get("lVAA12"))));
            map1.put("lVAC68", vac68);
            map1.put("lABBRP", PinyinHelper.getShortPinyin(GlobalVariable.StringIsNull(map1.get("lVAA05"))));
            // 更新病人资料信息
            if (obj0 == null || obj0.size()==0)
            {
                params.put("lVAA01", vaa01);
                registDao.insertVaa1(map1);
            }
            else
            {
                registDao.updateVAA1(map1);
            }
            // 新增病人挂号资料信息
            Long lvac01 = vaa01;
            params.put("lVAC01", lvac01);
            params.put("lBCE03A", "管理员");
            params.put("lVAC45", 1);
            params.put("lVAC34", 0);
            int curId = rateVac1Bo.Core_NewId_VAC02();
            String VAC02 = getNewSquenceNo(1, curId);
            map1.put("lVAC02", VAC02);
            registDao.insertVAC1(map1);
            // 新增挂号附表信息
            registDao.insertVCJ1(map1);
            // 插入门诊门诊病人收费单据表
            params.put("laVAI01", vaa01);
            registDao.insertVAI1(map1);
            // 生成门诊病人费用明细
            params.put("lVAJ01", vaa01);
            registDao.insertVAJ1(map1);
            
            mo.setResult(StaticKeys.OH_SUCCESS);
            return mo;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
    }
    
    /**
     *  系统号码生成,由系统独立序列号表管理>
     * @param AType
     * @param SquenceId
     * @return
     */
    public String getNewSquenceNo(int AType, int SquenceId) {
        String sStr = "";
        // ------------------------------挂号就诊号码生成------------------------------
        if (AType == 1) {
            // 如果挂号就诊独立序列号表初次使用，更新序列号值与挂号独立序列号表相同
            sStr = "0000000000";
            sStr = sStr + SquenceId;
            sStr = "R" + sStr.substring(sStr.length() - 10);
        }
        return sStr;
    }
    
    public ModelVo getABWList()
    {
        ModelVo mo = new ModelVo();
        try
        {
            List<Map<String, Object>> list = registDao.getABWList();
            mo.setList(list);
            mo.setResult(StaticKeys.OH_SUCCESS);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        return mo;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public ModelVo saveShouye(Map map)
    {
        ModelVo mo = new ModelVo();
        try
        {
            //病人挂号记录参数
            JSONObject vac1 = JSONObject.fromObject(map.get("VAC1").toString());
            Map param1 = (Map)JSONObject.toBean(vac1, Map.class);
            //更新病人挂号信息和病人基本信息
            registDao.updateVac1AndVaa1(param1);
            //根据姓名标识和信用记录标识更新资料变更记录
            if("1".equals(map.get("nameSign")))
            {
                param1.put("zae01", getNewId.nextId());
                registDao.insertZae1_name(param1);
            }
            if("1".equals(map.get("xinyongSign")))
            {
                param1.put("zae01", getNewId.nextId());
                registDao.insertZae1_xinyong(param1);
            }
            //根据挂号ID查询挂号附表记录
            Map<String,Object> temp = registDao.queryVcj1(param1);
            if(temp!=null)
            {
                registDao.updateVcj1(param1);//更新挂号附表
            }
            else
            {
                registDao.insertVcj1(param1);//挂号附表新增记录
            }
            //如果入院信息不为空
            if(Integer.parseInt(param1.get("BCK01").toString())!=0)
            {
                //查询对应的入院信息，如果为作废或者未入院，更新入院通知信息,否则新增。vbn12<=0
                List tempList1 = registDao.queryVbn1List(param1);
                if(tempList1!=null && tempList1.size()>0)
                {
                    registDao.updateVbn1(param1);
                }
                else
                {
                    registDao.insertVbn1(param1);
                }
                registDao.insertVbn1(param1);//入院通知表新增记录
            }
            //修改过敏药物信息
            JSONArray val1 = JSONArray.fromObject(map.get("VAL1").toString());
            List param2 = JsonUtil.parserToList(val1);
            for(int i = 0;i<param2.size();i++)
            {
                ((Map)param2.get(i)).put("val01", getNewId.nextId()+i);
            }
            Map param = new HashMap<>();
            param.put("param1", param1);
            param.put("param2", param2);
            registDao.updateVal1(param);
            //更新诊断信息
            JSONArray vao1 = JSONArray.fromObject(map.get("VAO1").toString());
            List param3 = JsonUtil.parserToList(vao1);
            map.put("param3", param3);
            List tempList1 = new ArrayList<>();//需要更新的
            List tempList2 = new ArrayList<>();//需要删除的
            List tempList3 = new ArrayList<>();//需要新增的
            for(Map temp99 : (List<Map>)param3)
            {
                if(Integer.parseInt(temp99.get("FSign").toString())==0)
                {
                    tempList1.add(temp99);
                }
                else if(Integer.parseInt(temp99.get("FSign").toString())==1)
                {
                    tempList2.add(temp99);
                }
                else if(Integer.parseInt(temp99.get("FSign").toString())==2)
                {
                    tempList3.add(temp99);
                }
            }
            param.put("tempList1", tempList1);
            param.put("tempList2", tempList2);
            for(int i = 0;i<tempList2.size();i++)
            {
                ((Map)tempList2.get(i)).put("vao01", getNewId.nextId());
                ((Map)tempList2.get(i)).put("vao06", i);
            }
            param.put("tempList3", tempList3);
            registDao.updateVao1(param);
            registDao.deleteVao1(param);
            registDao.insertVao1(param);
            //插入病人首页修改记录
            registDao.insertZiu1(param);
            mo.setResult(StaticKeys.OH_SUCCESS);
            return mo;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
    }
    
    /**
     * 将json串转换为map
     * 
     * @param mydata1
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map convertJson(String mydata1) {
        JSONArray jsonArray = JSONArray.fromObject(mydata1);
        JSONObject jsonJ = null;
        Map map = new HashMap();
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonJ = jsonArray.getJSONObject(i);
            String name = jsonJ.getString("name");
            String value = jsonJ.getString("value");
            map.put(name, value);
        }
        return map;
    }
    
    /**
     * json转JsonArray
     * 
     * @param jsonObject
     * @return
     * @throws Exception
     */
    public static List parserToMap(String jsonObject) throws Exception {
        return JsonUtil.getList(jsonObject);
    }
    
    /**
     *  计算明细年龄问题    小于14岁显示到月，小于1岁显示到天
     * @param VAA10
     * @param AAU01
     * @param VAA12
     * @return
     * @throws Exception
     */
    
    @SuppressWarnings({ "deprecation", "static-access" })
    public String GetAgeDetailFromAge(int VAA10, String AAU01, Date VAA12) throws Exception {
        String sAge = null;
        Date aDate = new Date();
        int amode = 0;
        int aYear = 0;
        int aMonth = 0;
        int aDay = 0;
        int bDay = 0;
        String rvalue = "";
        int ahour = 0;
        int amin = 0;
        Date t1 = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(t1);
        cal.add(Calendar.DAY_OF_MONTH, 1);
        Date tempDate = cal.getTime();
        VAA12 = (Date) (VAA12 == null ? tempDate : VAA12);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 可以方便地修改日期格式
        if (VAA12.getTime() - dateFormat.parse("1912-01-01").getTime() < 0) {
            if (VAA10 <= 0) {
                rvalue = "";
            } else {
                sAge = VAA10 + "";
                rvalue = sAge + AAU01;
            }
        } else {
            if (amode == 0) {
                aDay = dateDiff(VAA12, aDate, "day").intValue();
                if (aDay > 0) {
                    Calendar calaDate = Calendar.getInstance();
                    aMonth = dateDiff(VAA12, aDate, "month").intValue();
                    calaDate.setTime(aDate);
                    Calendar calVaa12 = Calendar.getInstance();
                    calVaa12.setTime(VAA12);
                    aDay = calaDate.get(calaDate.DAY_OF_MONTH) - calVaa12.get(calVaa12.DAY_OF_MONTH);
                    aYear = aMonth / 12;
                    aMonth = aMonth % 12;
                    if (aDay < 0) {
                        aMonth = aMonth - 1;
                    }
                    if (aMonth < 0) {
                        aYear = aYear - 1;
                        aMonth = 12 + aMonth;
                    }
                    if (aDay < 0) {
                        cal.setTime(VAA12);
                        cal.add(Calendar.MONTH, aMonth);// 增加一個月
                        cal.add(Calendar.YEAR, aYear);// 增加一個月
                        VAA12 = cal.getTime();
                        aDay = dateDiff(VAA12, aDate, "day").intValue();
                    }
                    if (aYear > 0) {
                        rvalue = rvalue + aYear + "Y";
                    }
                    if (aMonth > 0 && aYear < 14) {
                        rvalue = rvalue + aMonth + "M";
                    }
                    if (aDay > 0 && aYear < 1) {
                        rvalue = rvalue + aDay + "D";
                    }
                } else if (aDay == 0) {
                    amin = dateDiff(VAA12, aDate, "min").intValue();
                    if (amin > 0) {
                        ahour = amin / 60;
                        if (ahour == 0) {
                            rvalue = amin + "N";
                        } else if (ahour > 0) {
                            rvalue = ahour + "H";
                        }
                    }
                }

            } else {
                aYear = dateDiff(VAA12, aDate, "year").intValue();
                if (VAA12.getMonth() > aDate.getMonth()
                        || VAA12.getMonth() == aDate.getMonth() && VAA12.getDay() > aDate.getDay()) {
                    aYear = aYear - 1;
                    aMonth = dateDiff(VAA12, aDate, "month").intValue();
                }
                if (VAA12.getDay() > aDate.getDay()) {
                    aMonth = aMonth - 1;
                    aMonth = aMonth % 12;
                    cal.setTime(VAA12);
                    cal.add(Calendar.MONTH, 1);// 增加一個月
                    VAA12 = cal.getTime();
                    Calendar cal1 = Calendar.getInstance();
                    int day_of_month = cal1.get(Calendar.DAY_OF_MONTH);
                    cal1.add(Calendar.DATE, -day_of_month);
                    bDay = cal1.get(Calendar.DATE);
                    if (aYear > 0 || aMonth > 0 || (aYear <= 0 && aMonth <= 0) && VAA12.getDay() <= aDate.getDay()) {
                        aDay = Math.abs(aDate.getDay() - VAA12.getDay());
                    } else {
                        aDay = bDay - VAA12.getDay() + aDate.getDay();
                    }
                    if (aYear > 0) {
                        rvalue = rvalue + aYear + "Y";
                    }
                    if (aMonth > 0 && aYear < 14) {
                        rvalue = rvalue + aMonth + "M";
                    }
                    if (aDay > 0 && aYear < 1) {
                        rvalue = rvalue + aDay + "D";
                    }
                    if (dateDiff(VAA12, aDate, "day").intValue() < 0) {
                        rvalue = "";
                    }
                }

            }
        }
        return rvalue;
    }
    
    /**
     * 按指定日期单位计算两个日期间的间隔
     * 
     * @param timeInterval
     * @param date1
     * @param date2
     * @return
     */
    public static Long dateDiff(Date date2, Date date1, String timeInterval) {
        if (timeInterval.equals("year")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int time = calendar.get(Calendar.YEAR);
            calendar.setTime(date2);
            return (long) (time - calendar.get(Calendar.YEAR));
        }

        if (timeInterval.equals("quarter")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int time = calendar.get(Calendar.YEAR) * 4;
            calendar.setTime(date2);
            time -= calendar.get(Calendar.YEAR) * 4;
            calendar.setTime(date1);
            time += calendar.get(Calendar.MONTH) / 4;
            calendar.setTime(date2);
            return (long) (time - calendar.get(Calendar.MONTH) / 4);
        }

        if (timeInterval.equals("month")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int time = calendar.get(Calendar.YEAR) * 12;
            calendar.setTime(date2);
            time -= calendar.get(Calendar.YEAR) * 12;
            calendar.setTime(date1);
            time += calendar.get(Calendar.MONTH);
            calendar.setTime(date2);
            return (long) (time - calendar.get(Calendar.MONTH));
        }

        if (timeInterval.equals("week")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int time = calendar.get(Calendar.YEAR) * 52;
            calendar.setTime(date2);
            time -= calendar.get(Calendar.YEAR) * 52;
            calendar.setTime(date1);
            time += calendar.get(Calendar.WEEK_OF_YEAR);
            calendar.setTime(date2);
            return (long) (time - calendar.get(Calendar.WEEK_OF_YEAR));
        }

        if (timeInterval.equals("day")) {
            long time = Math.round(date1.getTime() / 1000 / 60 / 60 / 24);
            return time - Math.round(date2.getTime() / 1000.00 / 60.00 / 60.00 / 24.00);
        }

        if (timeInterval.equals("hour")) {
            long time = Math.round(date1.getTime() / 1000 / 60 / 60);
            return time - Math.round(date2.getTime() / 1000.00 / 60.00 / 60.00);
        }

        if (timeInterval.equals("minute")) {
            long time = Math.round(date1.getTime() / 1000 / 60);
            return time - Math.round(date2.getTime() / 1000.00 / 60.00);
        }

        if (timeInterval.equals("second")) {
            long time = Math.round(date1.getTime() / 1000);
            return time - Math.round(date2.getTime() / 1000.00);
        }

        return date1.getTime() - Math.round(date2.getTime());
    }

    @SuppressWarnings("unchecked")
    public ModelVo save_charge(Map<String, Object> params) throws Exception
    {
        ModelVo mo = new ModelVo();
        String mydata = (String)params.get("mydata");
        Map map1 = convertJson(mydata);
        
        List iar1List = registDao.queryForList("CliRegistration.hasIar1",map1);
        if(iar1List !=null && iar1List.size()>0)
        {
            mo.setResult(StaticKeys.OH_FALSE);
            mo.setResultMsg("此病人本次就诊已存在医保结账记录，不允许修改保险号和险种名称！");
            return mo;
        }
        Long vaa01 = getNewId.nextId();
        Long vac01 = getNewId.nextId();
        Long vai01 = getNewId.nextId();
        Object hasVaa01 = map1.get("lVAA01");
        if (map1.get("lVAA01")!=null)
        {
        	
            Map<String, Object> Vac71Obj = (Map<String, Object>)registDao.getVac71(map1);// // 获取就诊次数
            Integer vac71 = 0;
            if (Vac71Obj != null) {
                vac71/* 就诊次数 */ = Vac71Obj.get("vac71") == null ? 1 : Integer.parseInt(Vac71Obj.get("vac71").toString()) + 1;// 就诊次数+１
            } else {
                vac71 = 1;
            }
            if(vac71==0){
                vac71=1;
            }
            map1.put("lVAC71", vac71);
        }
        else
        {
        	Integer vaa03ct = (Integer)registDao.queryForExtObject("CliRegistration.getvaa03count", map1);
            if(vaa03ct>0){
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("此病人的门诊号有重复的,请检查对应的门诊号！");
                return mo;
            }
            map1.put("lVAA01", vaa01);
            map1.put("lVAC71", 1);
        }
        
        map1.put("lVAC01", vac01);
        map1.put("lVAI01", vai01);
        map1.put("lVAI04", "GH"+vai01);
        Object vac41 = map1.get("lVAC41");
        if(vac41!=null && !"".equals(vac41.toString()))
        {
            map1.put("lVAC41", Timestamp.valueOf(vac41.toString()));
        }
        else
        {
            map1.put("lVAC41", null);
        }
        if(map1.get("lVAA47")!=null)
        {
            map1.put("lVAC27", map1.get("lVAA47"));
        }
        String vaa12 = GlobalVariable.StringIsNull(map1.get("lVAA12"));
        if(!"".equals(vaa12))
        {
            map1.put("lVAA12", Timestamp.valueOf(vaa12));
        }
        else
        {
            map1.put("lVAA12", null);
        }
        String vaa10 = GlobalVariable.StringIsNull(map1.get("lVAA10"));
        if("".equals(vaa10))
        {
            map1.put("lVAA10", 0);
        }
        String vcj15 = GlobalVariable.StringIsNull(map1.get("lVCJ15"));
        if("".equals(vcj15))
        {
            map1.put("lVCJ15", 0);
        }
        String grid2rows = (String)params.get("grid2rows");
        List list1 = parserToMap(grid2rows);
        List<Long> vaj01s = getNewId.nextId(list1.size());
        double vaj37_sum = 0;
        for(int i = 0;i<list1.size();i++)
        {
            Map temp = (Map)list1.get(i);
            temp.put("lVAJ01", vaj01s.get(i));
            temp.put("lVAA01", vaa01);
            temp.put("lVAC01", vac01);
            temp.put("lVAI01", vai01);
            Object vaj37 = temp.get("vaj37");
            if(vaj37!=null && !"".equals(vaj37.toString()))
            {
                vaj37_sum = vaj37_sum + Double.parseDouble(vaj37.toString());
            }
            else
            {
                vaj37_sum += 0;
            }
        }
        map1.put("lVAJ37",vaj37_sum);
        map1.put("list1", list1);
        int totalNum = 1;
//        Object obj0 = null;
//            obj0 = registDao.queryVaa1(map1);
            
            // 判断病人性别是否符合科室性别限制
//            Object obj = registDao.queryBck1BySexAndBck01(map1);
//            if (obj != null)
//            {
//                mo.setResult(StaticKeys.OH_FALSE);
//                mo.setResultMsg("当前科室" + params.get("") + "限制只能挂性别为" + params.get("") + "的病人");
//                return mo;
//            }
            // 查询公共参数--简易挂号病人当天是否只能挂一次号
            Map<String, Object> temp = new HashMap<String, Object>();
            temp.put("productid", 100);
            temp.put("programid", 105002);
            temp.put("paramno", 253);
            String publicPara1 = cliParamterDao.getSysParamValue(temp);
            if (publicPara1!=null && "1".equals(publicPara1))
            {
                // 简易挂号病人当天是否只挂了一次号
                Object obj1 = registDao.queryVac1ByConditions(map1);
                if (obj1 != null)
                {
                    mo.setResult(StaticKeys.OH_FALSE);
                    mo.setResultMsg("同一个病人当天同一个科室同一个医生只能挂号一次，此病人已挂号，不能重复挂号");
                    return mo;
                }
            }
            
            // 病人是否满足免挂号条件
            // 获取病人免挂号岁数限制
            Map<String, Object> temp1 = new HashMap<String, Object>();
            temp1.put("productId", 100);
            temp1.put("programId", 105002);
            temp1.put("paramno", 367);
            String publicPara2 = cliParamterDao.getSysParamValue(temp1);
            Object obj2 = registDao.queryBBY1ByConditions(map1);
            if (publicPara2!=null)
            {
                int parseInt = Integer.parseInt(publicPara2);
                if (parseInt > 0 && "Y".equals(params.get("lAAU01"))
                    && Integer.parseInt(params.get("lVAA10").toString()) >= parseInt)
                {
                    if (obj2 != null)
                    {
                        // 删除病人费用明细表的挂号费用
                        registDao.deleteBBY1ByConditions(map1);
                    }
                } 
            }
            // 根据病人ID计算就诊次数
            // 如果挂号记录表存在病人ID，计算就诊次数
            Object obj3 = registDao.queryVac71(map1);
            if (obj3 != null)
            {
                totalNum = Integer.parseInt(obj3.toString()) + 1;
                params.put("totalNum", totalNum);
            }
            
            String vac68 = GetAgeDetailFromAge(0, "Y", DateUtils.String2Date(GlobalVariable.StringIsNull(map1.get("lVAA12"))));
            map1.put("lVAC68", vac68);
            map1.put("lABBRP", PinyinHelper.getShortPinyin(GlobalVariable.StringIsNull(map1.get("lVAA05"))));
            // 更新病人资料信息
            if ("".equals(GlobalVariable.StringIsNull(hasVaa01)))
            {
                params.put("lVAA01", vaa01);
                registDao.insertVaa1(map1);
            }
            else
            {
                registDao.updateVAA1(map1);
            }
            // 新增病人挂号资料信息
            Long lvac01 = vaa01;
            params.put("lVAC01", lvac01);
            params.put("lBCE03A", "管理员");
            params.put("lVAC45", 1);
            params.put("lVAC34", 0);
            int curId = rateVac1Bo.Core_NewId_VAC02();
            String VAC02 = getNewSquenceNo(1, curId);
            map1.put("lVAC02", VAC02);
            registDao.insertVAC1(map1);
            // 新增挂号附表信息
            registDao.insertVCJ1(map1);
            // 插入门诊门诊病人收费单据表
            params.put("laVAI01", vaa01);
            registDao.insertVAI1(map1);
            // 生成门诊病人费用明细
            params.put("lVAJ01", vaa01);
            registDao.insertVAJ1(map1);
            Map map4 = new HashMap();
            map4.put("productid", 9999);
            map4.put("programid", 9999);
            map4.put("paramno", 113);
            Map map426 = new HashMap();
            map426.put("productid", 100);
            map426.put("programid", 105002);
            map426.put("paramno", 426);
            Integer value4 = GlobalVariable.IntegerIsNull((cliParamterDao.getSysParamValue(map4)));
            Integer value426 = GlobalVariable.IntegerIsNull((cliParamterDao.getSysParamValue(map426)),0);
            int isPay = GlobalVariable.IntegerIsNull(params.get("isPay"),1);
            if (value4==1)
            {
                if ((isPay==1 && value426==1) || value426==0)
                {
                    //调用一卡通交易
                    List<Map<String, Object>> tempList =
                        JsonUtil.getList(GlobalVariable.StringIsNull(params.get("chargejson")));
                    //                for (Map<String, Object> temp0 : tempList)
                    //                {
                    if (tempList != null && !tempList.isEmpty())
                    {
                        
                        Map<String, Object> temp0 = tempList.get(0);
                        temp0.put("VAI01", vai01);
                        temp0.put("VAA01", map1.get("lVAA01"));
                        temp0.put("VAA07", map1.get("lVAC01"));
                        temp0.put("cardType", map1.get("cardType"));
                        mo = cardMemberMangerBo.updatehoratecardcharge(temp0);
                        if (mo.getResult().equals(StaticKeys.OH_FALSE))
                        {
                            throw new ExBaseException(mo.getResultMsg());
                            //                    }
                            
                        }
                    } 
                }
            }
            mo.setResult(StaticKeys.OH_SUCCESS);
            mo.setUserdata(vac01+"");;
            return mo;
    }
    
}
